package org.jvending.provisioning.dao.impl;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.jvending.provisioning.dao.BaseProvisioningDAO;
import org.jvending.provisioning.dao.DeliveryEventDAO;
import org.jvending.provisioning.model.deliveryevent.DeliveryEvent;
import org.jvending.registry.RepositoryRegistry;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;


public class DeliveryEventDAOImpl extends BaseProvisioningDAO implements DeliveryEventDAO {

    private static Logger logger = Logger.getLogger("DAO");

    private String dataSource = "hibernate3";

    public DeliveryEventDAOImpl(String className, String id) {
        super(className, id);
    }

    public void setRepositoryRegistry(RepositoryRegistry repositoryRegistry) {

    }

    public void store(DeliveryEvent deliveryEvent) throws IOException {
        Transaction transaction = null;
        Session session = null;
        try {
            session = getSessionFactoryByName(dataSource).openSession();

            transaction = session.beginTransaction();
            session.save(deliveryEvent);
            transaction.commit();
        } catch (Exception e) {
            try {
                if (transaction != null) transaction.rollback();
            } catch (HibernateException he) {
                logger.log(Level.INFO, "Failed to roll back transaction", he);
            }
            logger.log(Level.INFO, "Failed to save delivery event: " + deliveryEvent.toString(), e);
            throw new IOException("Failed to save delivery event: " + deliveryEvent.toString());
        } finally {
            try {
                if (session != null) session.close();
            } catch (HibernateException e) {
                logger.log(Level.INFO, "Failed to close session", e);
            }
        }
    }

}
